package com.xtayfjpk.zookeeper.test.master_workers.callback.client;

import org.apache.log4j.Logger;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.KeeperException.Code;
import org.apache.zookeeper.data.Stat;

import com.xtayfjpk.zookeeper.test.master_workers.Client;
import com.xtayfjpk.zookeeper.test.master_workers.TaskObject;
import com.xtayfjpk.zookeeper.test.master_workers.callback.BaseDataCallback;

public class GetTaskResultCallback extends BaseDataCallback {
	private static final Logger LOGGER = Logger.getLogger(GetTaskResultCallback.class);
	private Client client;
	public GetTaskResultCallback(Client client) {
		this.client = client;
	}

	@Override
	protected void connectionLossCaseAction(int rc, String path, Object ctx,
			byte[] data, Stat stat) {
		client.getTaskResult(path);
	}
	
	@Override
	protected void okCaseAction(int rc, String path, Object ctx, byte[] data, Stat stat) {
		String taskResult = new String(data);
		LOGGER.info("Task " + path + ", " + taskResult);
		
		assert(ctx != null);
		TaskObject.class.cast(ctx).setSuccessful(taskResult.contains("done"));
		
		client.deleteTaskResult(path);
	}
	
	@Override
	protected void noNodeCaseAction(int rc, String path, Object ctx,
			byte[] data, Stat stat) {
		LOGGER.warn("Status node is gone!");
	}
	
	@Override
	protected void defaultCaseAction(int rc, String path, Object ctx,
			byte[] data, Stat stat) {
		LOGGER.error("Something went wrong here, " + 
                KeeperException.create(Code.get(rc), path));   
	}
}
